package cn.edu.dyxy.controller;

import cn.edu.dyxy.entity.User;
import cn.edu.dyxy.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author JokerQiu
 * @date 2021年12月23日 11:03
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    private UserService userService = new UserService();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("loginServlet");
        /**
         * 1、获取数据
         * 2、调用业务层中的登陆
         * 3、返回结果数据
         */
        //1、获取数据
        String email = req.getParameter("email");
        String password = req.getParameter("password");
        //2、调用业务层
        User user = userService.login(email, password);
        //3、返回结果
        if (user != null) {
            HttpSession session = req.getSession();
            session.setAttribute("user", user);
            session.setAttribute("nickname", user.getNickname());
            //重定向到新的页面
            resp.sendRedirect("bookList");
        } else {
            req.setAttribute("errorMsg", "用户名或密码错误");
            //转发，重新回到登陆界面
            req.getRequestDispatcher("login.jsp").forward(req, resp);
        }

    }
}
